<?php

class TugasAkhirController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','download'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new TugasAkhir;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TugasAkhir']))
                {
                    $model->attributes=$_POST['TugasAkhir'];
                    $model->downloaded=0;
                    date_default_timezone_set('Asia/Jakarta');
                    $model->uploadtime= date('Y-m-d H:i:s', time());
                    
                    $rnd = rand(0,9999);
                    $uploadedFile=  CUploadedFile::getInstance($model, 'PosterPath');
                    $fileName = "{$rnd}-{$uploadedFile}";
                    $model->PosterPath = $fileName;
                    
                    
                    if($model->save())
                    {
                        $uploadedFile->saveAs(Yii::app()->basePath.'/../data_posterMhs/'. $model->PosterPath);
                        // image will uploaded to rootDirectory/data_posterMhs/
                        //$this->redirect(array('admin'));
                        if(isset($_POST['tag_1'])){
                            $tag_1 = $_POST['tag_1'];                       
                             
                            if ($record != null){
                                $id_tag = $record[0]['id_tag'];
                                Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                            }
                        }
                        if(isset($_POST['tag_2'])){
                            $tag_2 = $_POST['tag_2'];                       
                            $record = Yii::app()->db->createCommand()
                            ->select('id_tag')
                            ->from('tag')
                            ->where("tag='$tag_2'")
                            ->queryAll();
                            if ($record != null){
                                $id_tag = $record[0]['id_tag'];
                                Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                            }
                        }
                        if(isset($_POST['tag_3'])){
                            $tag_3 = $_POST['tag_3'];                       
                            $record = Yii::app()->db->createCommand()
                            ->select('id_tag')
                            ->from('tag')
                            ->where("tag='$tag_3'")
                            ->queryAll();
                           if ($record != null){
                                $id_tag = $record[0]['id_tag'];
                                Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                            }
                        }
                        if(isset($_POST['tag_4'])){
                            $tag_4 = $_POST['tag_4'];                       
                            $record = Yii::app()->db->createCommand()
                            ->select('id_tag')
                            ->from('tag')
                            ->where("tag='$tag_4'")
                            ->queryAll();
                            if ($record != null){
                                $id_tag = $record[0]['id_tag'];
                                Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                            }
                        }
                        if(isset($_POST['tag_5'])){
                            $tag_5 = $_POST['tag_5'];                       
                            $record = Yii::app()->db->createCommand()
                            ->select('id_tag')
                            ->from('tag')
                            ->where("tag='$tag_5'")
                            ->queryAll();
                            if ($record != null){
                                $id_tag = $record[0]['id_tag'];
                                Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                            }
                        }
                        
                        //Dosen Pembimbing
                        if(isset($_POST['dos_bing'])){                            
                            $nik = $_POST['dos_bing'];
                            $email = Yii::app()->user->getId();
                            $record = Yii::app()->db->createCommand()
                            ->select('nim')
                            ->from('mahasiswa')
                            ->where("email='$email'")
                            ->queryAll();
                            $nim = $record[0]['nim'];
                            Yii::app()->db->createCommand("insert into membimbing values ('$nim','$nik',$model->ID_TA)")->execute();
                        }
                    }					
                }
                //$this->redirect(array('view','id'=>$model->ID_TA));
                $this->render('create',array('model'=>$model,));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
                $tag1 = null;
                $tag2 = null;
                $tag3 = null;
                $tag4 = null;
                $tag5 = null;
                $dosbing = null;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['TugasAkhir']))
		{
                        $_POST['TugasAkhir']['PosterPath'] = $model->PosterPath;
                        $model->attributes=$_POST['TugasAkhir'];
 
                        $uploadedFile=CUploadedFile::getInstance($model,'PosterPath');

			if($model->save())
                        {
                            if(!empty($uploadedFile))  // check if uploaded file is set or not
                            {
                                $uploadedFile->saveAs(Yii::app()->basePath.'/../data_posterMhs/'.$model->PosterPath);
                            }
                            
                            $query = "delete from `ta_tag` where `ID_TA` = $model->ID_TA";
                            yii::app()->db->createCommand($query)->execute();
                            if(isset($_POST['tag_1'])){
                                $tag_1 = $_POST['tag_1'];
                                $tag1 = $tag_1;
                                $record = Yii::app()->db->createCommand()
                                ->select('id_tag')
                                ->from('tag')
                                ->where("tag='$tag_1'")
                                ->queryAll();
                                if ($record != null){
                                    $id_tag = $record[0]['id_tag'];
                                    Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                                }
                            }
                            if(isset($_POST['tag_2'])){
                                $tag_2 = $_POST['tag_2'];   
                                $tag2 = $tag_2;
                                $record = Yii::app()->db->createCommand()
                                ->select('id_tag')
                                ->from('tag')
                                ->where("tag='$tag_2'")
                                ->queryAll();
                                if ($record != null){
                                    $id_tag = $record[0]['id_tag'];
                                    Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                                }
                            }
                            if(isset($_POST['tag_3'])){
                                $tag_3 = $_POST['tag_3']; 
                                $tag3 = $tag_3;
                                $record = Yii::app()->db->createCommand()
                                ->select('id_tag')
                                ->from('tag')
                                ->where("tag='$tag_3'")
                                ->queryAll();
                               if ($record != null){
                                    $id_tag = $record[0]['id_tag'];
                                    Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                                }
                            }
                            if(isset($_POST['tag_4'])){
                                $tag_4 = $_POST['tag_4'];  
                                $tag4 = $tag_4;
                                $record = Yii::app()->db->createCommand()
                                ->select('id_tag')
                                ->from('tag')
                                ->where("tag='$tag_4'")
                                ->queryAll();
                                if ($record != null){
                                    $id_tag = $record[0]['id_tag'];
                                    Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                                }
                            }
                            if(isset($_POST['tag_5'])){
                                $tag_5 = $_POST['tag_5']; 
                                $tag5 = $tag_5;
                                $record = Yii::app()->db->createCommand()
                                ->select('id_tag')
                                ->from('tag')
                                ->where("tag='$tag_5'")
                                ->queryAll();
                                if ($record != null){
                                    $id_tag = $record[0]['id_tag'];
                                    Yii::app()->db->createCommand("insert into ta_tag values ($model->ID_TA,$id_tag)")->execute();
                                }
                            }
                        
                            //Dosen Pembimbing
                            if(isset($_POST['dos_bing'])){                            
                                $nik = $_POST['dos_bing'];
                                $dosbing = $nik;
                                Yii::app()->db->createCommand("update membimbing set NIP = '$nik' where ID_TA = $model->ID_TA")->execute();
                            }
                            $this->redirect(array('admin'));
                        }  
		}
                $this->render('update',array(
                            'model'=>$model, 
                            'tag_1' => $tag1,
                            'tag_2' => $tag2,
                            'tag_3' => $tag3,
                            'tag_4' => $tag4,
                            'tag_5' => $tag5,
                            'dos_bing' => $dosbing,
                        ));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	
	public function actionDownload($id)
	{
		$this->render('download',array(
			'id'=>$id,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('TugasAkhir');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new TugasAkhir('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TugasAkhir']))
			$model->attributes=$_GET['TugasAkhir'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=TugasAkhir::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tugas-akhir-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
